package com.tantou.java.structandalgorithm.search;

import java.util.Arrays;

/**
 * 二分查找
 * 针对的是有序集合
 *
 * 二分查找虽然性能比较优秀，但应用场景也比较有限。底层必须依赖数组，并且还要求数据是有序的。对于较小规模的数据查找，我们直接使用顺序遍历就可以了，二分查找的优势并不明显。二分查找更适合处理静态数据，也就是没有频繁的数据插入、删除操作。
 */
public class BinarySearch {

    public static void main(String[] args) {
        int[] arr = {1, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
        int idx = research(arr, 9);
        System.out.println(idx);
    }

    public static int search(int[] nums, int target) {
        Arrays.sort(nums);

        int low = 0;
        int high = nums.length-1;
        while(low<=high){
            int mid = (low+high)/2;
            if(nums[mid]==target){
                return mid;
            }else if(nums[mid]>target){
                //如果中间数大于目标值，说明在左边
                high = mid-1;
            }else{
                low = mid+1;
            }
        }
        return -1;
    }

    public static int research(int[] nums,int target){
        return doSearch(nums,target,0,nums.length-1);

    }

    private static int doSearch(int[] nums, int target, int low, int high) {
        int mid = (low+high)/2;
        if(nums[mid]==target){
            return mid;
        }else if(nums[mid]>target){
            return doSearch(nums,target,low,mid-1);
        }else{
            return doSearch(nums,target,mid+1,high);
        }
    }

}
